package notice

import (
	"strings"
	"time"

	"gddgame.cc/galaxy/binocle/plugins/wechat"
	"gddgame.cc/galaxy/utils"
	"gddgame.cc/galaxy/utils/def"
)

func SendNotice(context def.Context, publish string, data map[string]interface{}) error {
	var noticeList []Notice
	p := strings.Split(publish, ".")
	subscribes := make([]string, len(p))
	// 计算所有符合规则的subscribe
	// a.b.c => a.* a.b.* a.b.c
	for i := 0; i < len(p); i++ {
		s := strings.Join(p[0:i+1], ".")
		if i != len(p)-1 {
			s += ".*"
		}
		subscribes[i] = s
	}
	// a.b.c => *.b.* *.b.c *.c
	if _, err := NoticeModel.Query().
		Where("in", "subscribe", subscribes).
		Where("=", "status", 1).
		Find(&noticeList); err != nil {
		context.Debugf("[ Notice ] Publish: %s not match subscribe (%s)", publish, subscribes)
		return err
	}
	context.Debugf("[ Notice ] Publish: %s match %d subscribe (%s)", publish, len(noticeList), subscribes)
	now := time.Now()
	data["time"] = now.Format("15:04:05")
	data["date"] = now.Format("2006-01-02")
	for _, notice := range noticeList {
		message := notice.Template
		for key, value := range data {
			message = strings.Replace(message, `{`+key+`}`, utils.ToString(value), 1)
		}
		switch notice.Type {
		case WechatNoticeType:
			// 发送微信消息
			_ = wechat.PushWechat(context, notice.Target, message)
		}
	}
	return nil
}
